package com.hopes.bizz.risk.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hopes.bizz.common.core.annotation.TenantJobRun;
import com.hopes.bizz.risk.integral.entity.RiskIntegralRecordEntity;
import com.hopes.bizz.risk.integral.entity.RiskIntegralStatisticalEntity;
import com.hopes.bizz.risk.integral.service.RiskIntegralRecordService;
import com.hopes.bizz.risk.integral.service.RiskIntegralStatisticalService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/8/8 16:44
 * @Description: 统计员工积分任务
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RiskIntegralService {

    private final RiskIntegralRecordService riskIntegralRecordService;

    private final RiskIntegralStatisticalService riskIntegralStatisticalService;

    @TenantJobRun
    @Transactional(rollbackFor = Exception.class)
    @XxlJob("riskIntegralJobHandler")
    public void riskIntegralJobHandler() {
        long start = System.currentTimeMillis();
        log.info("----------------统计员工积分任务----------------`");

        // 昨天开始时间和结束时间
        Date nowDate = new Date();
        Date date = DateUtil.offsetDay(nowDate, -1);
        Date beginDate = DateUtil.beginOfDay(date);
        Date endDate = DateUtil.endOfDay(date);
        // 处理积分统计
        handleDayIntegral(beginDate, endDate);

        log.info("----------------统计员工积分任务结束,结果为={},耗时(毫秒)={}----------------`", true, System.currentTimeMillis() - start);
        // 设置任务结果
        XxlJobHelper.handleSuccess();
    }

    private void handleDayIntegral(Date beginDate, Date endDate) {
        log.debug("开始统计昨日数据...：{}，{}", beginDate, endDate);
        LambdaQueryWrapper<RiskIntegralRecordEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.ge(RiskIntegralRecordEntity::getStatisticalDate, beginDate);
        wrapper.le(RiskIntegralRecordEntity::getStatisticalDate, endDate);

        List<RiskIntegralRecordEntity> hidIntegralRecords = riskIntegralRecordService.list(wrapper);
        if (CollectionUtil.isNotEmpty(hidIntegralRecords)) {
            Map<Long, List<RiskIntegralRecordEntity>> map = hidIntegralRecords.stream().collect(Collectors.groupingBy(RiskIntegralRecordEntity::getAccountId));
            map.forEach((account, list) -> {
                if (account != null) {
                    int addIntegral = 0;
                    int deduceIntegral = 0;
                    for (RiskIntegralRecordEntity hidIntegralRecord : list) {
                        Integer integral = hidIntegralRecord.getIntegral();
                        if (integral >= 0) {
                            addIntegral += integral;
                        } else {
                            deduceIntegral += integral;
                        }
                    }
                    int count = addIntegral + deduceIntegral;
                    RiskIntegralStatisticalEntity hidIntegralStatistical = riskIntegralStatisticalService.getByAccount(account);
                    if (hidIntegralStatistical == null) {
                        RiskIntegralStatisticalEntity saveWrapper = new RiskIntegralStatisticalEntity();
                        saveWrapper.setAccountId(account);
                        saveWrapper.setIntegral(count);
                        saveWrapper.setDeductIntegral(deduceIntegral * -1);
                        saveWrapper.setEarnIntegral(addIntegral);
                        saveWrapper.setExchangeableIntegral(count);
                        riskIntegralStatisticalService.save(saveWrapper);
                    } else {
                        Integer integral = hidIntegralStatistical.getIntegral();
                        Integer deductIntegral = hidIntegralStatistical.getDeductIntegral();
                        Integer earnIntegral = hidIntegralStatistical.getEarnIntegral();
                        Integer exchangeableIntegral = hidIntegralStatistical.getExchangeableIntegral();
                        hidIntegralStatistical.setIntegral(integral + count);
                        hidIntegralStatistical.setDeductIntegral(deductIntegral + (deduceIntegral * -1));
                        hidIntegralStatistical.setEarnIntegral(earnIntegral + addIntegral);
                        hidIntegralStatistical.setExchangeableIntegral(exchangeableIntegral + count);
                        riskIntegralStatisticalService.updateById(hidIntegralStatistical);
                    }
                }
            });
        }
        log.debug("统计结束");
    }
}
